package com.deyinet.bdcms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.deyinet.bdcms.controller.dtoandapi.ExcelDataApi;
import com.deyinet.bdcms.core.vo.Page;
import com.deyinet.bdcms.entity.*;
import com.deyinet.bdcms.service.IDevicedataService;
import com.deyinet.bdcms.service.ILogsService;
import com.deyinet.bdcms.service.ISysmoduleService;
import com.deyinet.bdcms.tools.CheckNull;
import com.deyinet.bdcms.tools.FileTool;
import com.deyinet.bdcms.tools.WebUtilify;
import com.deyinet.bdcms.tools.objListToExcel;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Bacel on 2017/05/02.
 */
@Controller
@RequestMapping(value = "/sysmanage/devicedata", produces = "text/html;charset=UTF-8")
public class devicedataController {
    private final Logger logger = Logger.getLogger(devicedataController.class);

    @Autowired
    private ISysmoduleService sysmoduleService;
    @Autowired
    private IDevicedataService moduleService;
    @Autowired
    private ILogsService logsService;

    private int aa = 0;


    @RequestMapping(value = "/list")
    public void list() {
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public void add() {
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String edit(@RequestBody Devicedata module, final HttpServletRequest request) {
        String ret = "";
        String errstr = "";
        Syslog log = new Syslog();
        Sysmodule sysmodule = new Sysmodule();
        try {
            if (module != null) {
                if (module.getCreatedate() == null)
                    module.setCreatedate(new Timestamp(System.currentTimeMillis()));
                if (module.getId() != null) {
                    module.setCreatedate(new Timestamp(System.currentTimeMillis()));
                    this.moduleService.updateT(module);
                    log.setTitle("修改设备数据");
                } else {
                    this.moduleService.insertT(module);
                    log.setTitle("添加设备数据");
                }
                sysmodule.setId(5);
                log.setSysmoduleByModuleid(sysmodule);
                log.setSysuserByUserid(WebUtilify.LoginUserinfo(request));
                log.setContent(JSON.toJSONString(module));
                log.setCreatedate(new Timestamp(System.currentTimeMillis()));
                WebUtilify.WriteLog(request,log, logsService);
            }
        } catch (Exception ex) {
            //logger.error(ex,"editdevicedata","更新渠道错误","");
            errstr = "操作失败001";
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

    @RequestMapping(value = "/listdata")
    @ResponseBody
    public String listdata(final HttpServletRequest request, Page<Devicedata> page) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String deviceName = request.getParameter("deviceName");
        String sn = request.getParameter("sn");
        String ownerName = request.getParameter("ownerName");
        String devicetypeName = request.getParameter("devicetypeName");
        String createdatestart = request.getParameter("createdatestart");
        String createdateend = request.getParameter("createdateend");
        Timestamp ts = null;
        if (createdatestart != null && !"".equals(createdatestart)) {
            ts = new Timestamp(format.parse(createdatestart).getTime());//string-->Timestamp
        }
        Timestamp te = null;
        if (createdateend != null && !"".equals(createdateend)) {
            te = new Timestamp(format.parse(createdateend).getTime());//string-->Timestamp
        }
        Devicedata devicedata = new Devicedata();
        Device device = new Device();
        if (deviceName != null && !"".equals(deviceName)) {
            device.setDevicename(deviceName);
            devicedata.setDeviceByDevicesn(device);
        }
        Deviceowner deviceowner = new Deviceowner();
        if (ownerName != null && !"".equals(ownerName)) {
            deviceowner.setName(ownerName);
            device.setDeviceownerByOwnerid(deviceowner);
            devicedata.setDeviceByDevicesn(device);
        }
        if (devicetypeName != null && !"".equals(devicetypeName)) {
            device.setDevicemodel(devicetypeName);
            devicedata.setDeviceByDevicesn(device);
        }
        if (sn != null && !"".equals(sn)) {
           devicedata.setSn(sn);
        }
        moduleService.findByExampleLike(devicedata, page, ts, te);
        Map<String, Object> info = new HashMap<>();
        info.put("totalRow", page.getTotalRow());
        info.put("pageCurrent", page.getPageCurrent());
        info.put("list", page.getList());
        String ret = JSON.toJSONString(info, SerializerFeature.DisableCircularReferenceDetect);// JSONArray.toJSONString(datamodule);
        return ret;
    }


    @RequestMapping(value = "/listdataimport")
    public void listdataimport(final HttpServletRequest request, final HttpServletResponse response) throws ParseException, IOException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String deviceName = request.getParameter("deviceName2");
        String ownerName = request.getParameter("ownerName2");
        String devicetypeName = request.getParameter("devicetypeName2");
        String createdatestart = request.getParameter("createdatestart2");
        String createdateend = request.getParameter("createdateend2");
        Timestamp ts = null;
        if (createdatestart != null && !"".equals(createdatestart)) {
            ts = new Timestamp(format.parse(createdatestart).getTime());//string-->Timestamp
        }
        Timestamp te = null;
        if (createdateend != null && !"".equals(createdateend)) {
            te = new Timestamp(format.parse(createdateend).getTime());//string-->Timestamp
        }
        Devicedata devicedata = new Devicedata();
        Device device = new Device();
        if (deviceName != null && !"".equals(deviceName)) {
            device.setDevicename(deviceName);
            devicedata.setDeviceByDevicesn(device);
        }
        Deviceowner deviceowner = new Deviceowner();
        if (ownerName != null && !"".equals(ownerName)) {
            deviceowner.setName(ownerName);
            device.setDeviceownerByOwnerid(deviceowner);
            devicedata.setDeviceByDevicesn(device);
        }
        if (devicetypeName != null && !"".equals(devicetypeName)) {
            device.setDevicemodel(devicetypeName);
            devicedata.setDeviceByDevicesn(device);
        }

        List<Devicedata> list = moduleService.findByExampleLikeImport(devicedata, ts, te);
        List<ExcelDataApi> listData = null;
        if (list.size() > 0) {
            listData = setToExcelApi(list);
            Map<String, Object> map = new HashedMap();
            Map<String, String> ziDuan = new HashMap();
            ziDuan.put("0id", "id");
            ziDuan.put("1sn", "sn");
            ziDuan.put("2report", "水位值");
            ziDuan.put("3voltage", "电压值");
            ziDuan.put("4status", "状态");
            ziDuan.put("5createdate", "上报时间");
            ziDuan.put("6deviceName", "设备名称");
            ziDuan.put("7ownerName", "所属用户");
            ziDuan.put("8location", "位置");
            ziDuan.put("9deviceModel", "设备型号");
            map.put("listData", listData);
            map.put("ziDuan", ziDuan);
            File file = objListToExcel.objListToExcel("设备数据导出", map);
            byte[] b = FileTool.getBytesFromFile(file);
            //以字符流的形式下载文件
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=data-"+format.format(new Date())+".xls");
            response.addHeader("content-type","utf-8");
            response.addHeader("Content-Length", "" + b.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(b);
            toClient.flush();
            toClient.close();
        }
    }

    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, Object> del(String json, HttpServletRequest request) {
        List<Devicedata> devicedatalist = JSONArray.parseArray(json, Devicedata.class);
        Syslog log = new Syslog();
        Sysmodule sysmodule = new Sysmodule();
        Integer[] idarr = new Integer[devicedatalist.size()];
        for (int i = 0; i < devicedatalist.size(); i++) {
            idarr[i] = devicedatalist.get(i).getId();
        }
        moduleService.batchDelete(idarr);
        log.setTitle("删除设备数据");
        sysmodule.setId(5);
        log.setSysmoduleByModuleid(sysmodule);
        log.setSysuserByUserid(WebUtilify.LoginUserinfo(request));
        log.setContent(JSON.toJSONString(devicedatalist));
        log.setCreatedate(new Timestamp(System.currentTimeMillis()));
        WebUtilify.WriteLog(request,log, logsService);

        Map<String, Object> info = new HashMap<>();
        info.put("message", "删除成功");
        info.put("status", 200);
        info.put("closeCurrent", "false");
        return info;
    }


    @RequestMapping(value = "/getmodule", method = RequestMethod.GET)
    public String getmodule(final HttpServletRequest request)
            throws Exception {
        Integer id = Integer.parseInt(request.getParameter("id"));
        Devicedata module = this.moduleService.get(id);
        if (module != null)
            return JSON.toJSONString(module);
        return "";
    }

    @RequestMapping(value = "/statistics")
    @ResponseBody
    public Map<String, Integer> statistics(final HttpServletRequest request, String startTime, String endTime)
            throws Exception {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp start = null;
        Timestamp end = null;
        if (CheckNull.check(startTime)) {
            start = new Timestamp(sdf.parse(startTime).getTime());
        }
        if (CheckNull.check(endTime)) {
            end = new Timestamp(sdf.parse(endTime).getTime());
        }
        return moduleService.statistics(start, end);
    }

    private List<ExcelDataApi> setToExcelApi(List<Devicedata> list) {
        List<ExcelDataApi> apis = new ArrayList<>();
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Devicedata devicedata : list) {
            ExcelDataApi api = new ExcelDataApi();
            api.setId(devicedata.getId());
            api.setSn(devicedata.getSn());
            api.setReport(devicedata.getReport());
            api.setVoltage(devicedata.getVoltage());
            api.setStatus(switchStatus(devicedata.getStatus()));
            api.setCreatedate(sdf.format(devicedata.getCreatedate()));

            Device device = devicedata.getDeviceByDevicesn();
            if (device != null) {
                api.setDeviceName(device.getDevicename());
                api.setLocation(device.getLocation());
                api.setDeviceModel(device.getDevicemodel());
                if (device.getDeviceownerByOwnerid() != null) {
                    api.setOwnerName(device.getDeviceownerByOwnerid().getName());
                }
                apis.add(api);
            }
        }
        return apis;
    }

    private String switchStatus(int status) {
        switch (status) {
            case 1:
                return "设备正常";
            case 2:
                return "设备正常";
            case 3:
                return "设备正常";
            case 4:
                return "设备正常";
            case 5:
                return "设备正常";
        }
        return null;
    }


}